package pub.tbc.api.service.discovery;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.api.cache.CacheProvider;
import pub.tbc.api.cache.ServiceCache;
import pub.tbc.api.service.balancing.DefaultLoadBalancing;
import pub.tbc.api.service.balancing.LoadBalancing;
import pub.tbc.toolkit.Objs;

import java.util.List;
import java.util.Map;

/**
 * 本地缓存服务发现机制: 服务地址只通过缓存获取，而缓存的维护任务不管
 *
 * @author tbc on 2017/3/22 14:46:28.
 */
@Slf4j
public class NativeCacheDiscovery implements ServiceDiscovery {
    private ServiceCache cache = CacheProvider.getServiceCache();
    private LoadBalancing balancing = new DefaultLoadBalancing();

    @Override
    public String discover(String serviceName) {
        List<Map<String, Integer>> sourceAddresses = cache.get(serviceName);
        if (Objs.isEmpty(sourceAddresses)) {
            throw new RuntimeException("服务地址未发现");
        }
        // 防御性复制，防止在获取地址的过程中服务地址列表被更改
        List<Map<String, Integer>> addresses = Lists.newArrayList(cache.get(serviceName));
        return balancing.weighRandom(addresses);
    }
}
